package com.example.demo.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author lvyk
 * @Description: 供过滤器使用的工具类
 * @Date 2020/5/27 14:05
 * @Modify By:
 */
@Component
@Slf4j
public class FilterUtil {

    /**
     * BASE64加密
     */
    public String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    /**
     * BASE64解密
     */
    public byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }

    public static String getRequestBody(HttpServletRequest req) {
        try {

            BufferedReader reader = req.getReader();
            StringBuffer sb = new StringBuffer();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            String json = sb.toString().substring(9, sb.toString().length()-1);
            return json;
        } catch (IOException e) {
            log.error("验签时请求体读取失败", e);
        }
        return "";
    }

    public void writeResponse(ServletResponse response, String responseString) throws IOException {
        PrintWriter out = response.getWriter();
        out.print(responseString);
        out.flush();
        out.close();
    }


}
